// eventManager.ts
type Subscription = {
	readonly instance?: any;
	readonly callback: Function;
	readonly isDebug?: boolean;
};

type EventMap = {
	[event: string]: Subscription[];
};

type SubscriptionInfo = {
	eventName: string;
	subscriptionCount: number;
	subscribers: Subscription[];
};

type InstanceSubscriptionInfo = {
	eventName: string;
	callbackNames: string[];
};

export const eventManager = {
	_events: {} as EventMap,

	on(eventName: string, callback: Function, instance?: any) {
		if (!this._events[eventName]) {
			this._events[eventName] = [];
		}

		const exists = this._events[eventName].some(
			(sub: { instance: any; callback: Function; }) => sub.instance === instance && sub.callback === callback
		);

		if (!exists) {
			this._events[eventName].push({ instance, callback });
		}
	},

	off(eventName: string, callback: Function, instance?: any) {
		if (this._events[eventName]) {
			this._events[eventName] = this._events[eventName].filter(
				(sub: { instance: any; callback: Function; }) => !(sub.instance === instance && sub.callback === callback)
			);
		}
	},

	emit(eventName: string, ...args: any[]) {
		const subscriptions = this._events[eventName] || [];
		subscriptions.forEach(({ callback }: Subscription) => {
			try {
				callback(...args);
			} catch (e) {
				console.error(`事件处理错误 [${eventName}]:`, e);
			}
		});
	},

	unsubscribeAll(instance?: any) {
		Object.keys(this._events).forEach(eventName => {
			this._events[eventName] = this._events[eventName].filter(
				(sub: { instance: any; }) => sub.instance !== instance
			);
		});
	},

	getSubscriptions(targetEvent?: string): SubscriptionInfo[] {
		if (targetEvent) {
			return [{
				eventName: targetEvent,
				subscriptionCount: this._events[targetEvent]?.length || 0,
				subscribers: this._events[targetEvent] || []
			}];
		}

		return Object.keys(this._events).map(eventName => ({
			eventName,
			subscriptionCount: this._events[eventName].length,
			subscribers: this._events[eventName]
		}));
	},

	getInstanceSubscriptions(instance: any): InstanceSubscriptionInfo[] {
		const result: InstanceSubscriptionInfo[] = [];

		// 添加类型断言
		(Object.entries(this._events) as [string, Subscription[]][]).forEach(([eventName, subscriptions]) => {
			const instanceSubs = subscriptions
				.filter((sub: Subscription) => sub.instance === instance)
				.map(sub => ({
					name: sub.callback.name || '匿名函数',
					toString: sub.callback.toString()
				}));

			if (instanceSubs.length > 0) {
				result.push({
					eventName,
					callbackNames: instanceSubs.map(sub => sub.name)
				});
			}
		});

		return result;
	}
};